package com.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.model.Admin;
import com.service.AdminService;
import com.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin("*")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 添加管理员接口
     */
    @PostMapping("/admins")
    public Result addAdmin(@RequestBody Admin admin) {
        boolean result = adminService.save(admin);
        if (result){
            return new Result("200","添加成功",1,null);
        } else {
            return new Result("500","添加失败,请联系管理员询问原因",0,null);
        }
    }

    /**
     * 根据ID删除管理员接口
     */
    @DeleteMapping("/admins/{id}")
    public Result deleteAdminById(@PathVariable Integer id) {
        boolean result = adminService.removeById(id);
        if (result){
            return new Result("200","删除成功",1,null);
        } else {
            return new Result("500","删除失败",0,null);
        }
    }

    /**
     * 根据管理员 ID 查询管理员
     * @param id 管理员 ID
     * @return 返回查询到的管理员对象
     */
    @GetMapping("/admins/{id}")
    public Result getAdminById(@PathVariable("id") Integer id) {
        Admin admin = adminService.getOne(new QueryWrapper<Admin>().eq("id", id));
        return new Result("200","查询成功",1, List.of(admin));
    }

    /**
     * 根据ID或账号查询单个管理员接口
     */
    /*@GetMapping("/admins/{idOrAccount}")
    public Result getAdminByIdOrAccount(@PathVariable String idOrAccount) {
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.and(i -> i.eq("id", idOrAccount)
                .or()
                .eq("account", idOrAccount));
        Admin admin = adminService.getOne(wrapper);
        return new Result("200","查询成功",1, List.of(admin));
    }*/

    /**
     * 查询全部管理员接口
     */
    @GetMapping("/admins")
    public Result getAllAdmins() {
        List<Admin> list = adminService.list();
        return new Result("200","查询成功",list.size(),list);
    }

    /**
     * 分页查询管理员接口
     */
    @GetMapping("/admins/page/{pageNum}/{pageSize}")
    public IPage<Admin> getAdminsByPage(@PathVariable Integer pageNum, @PathVariable Integer pageSize) {
        return adminService.page(new Page<>(pageNum, pageSize), null);
    }

    /**
     * 根据ID更新管理员接口
     */
    @PutMapping("/admins/{id}")
    public Result updateAdminById(@PathVariable Integer id, @RequestBody Admin admin) {
        admin.setId(id);
        boolean result = adminService.updateById(admin);
        if (result){
            return new Result("200","更新成功",1,List.of(admin));
        } else {
            return new Result("500","更新失败",0,null);
        }
    }

}

